package com.liferay.portal.service;

import java.io.InputStream;
import java.util.Locale;

import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.search.Indexer;
import com.liferay.portal.kernel.search.IndexerRegistryUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.PropsUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.Group;
import com.liferay.portal.model.Layout;
import com.liferay.portal.model.LayoutConstants;
import com.liferay.portal.model.Organization;
import com.liferay.portal.model.OrganizationConstants;
import com.liferay.portal.model.PortletConstants;
import com.liferay.portal.model.Role;
import com.liferay.portal.model.RoleConstants;
import com.liferay.portal.model.User;
import com.liferay.portal.model.UserGroup;
import com.liferay.portal.service.permission.PortletPermissionUtil;
import com.liferay.portal.theme.ThemeDisplay;

public class ExtUserLocalService extends UserLocalServiceWrapper {
	
	public ExtUserLocalService(UserLocalService userLocalService) {
		super(userLocalService);
	}
	
	@Override
	public User addUser(long creatorUserId, long companyId,
			boolean autoPassword, String password1, String password2,
			boolean autoScreenName, String screenName, String emailAddress,
			long facebookId, String openId, Locale locale, String firstName,
			String middleName, String lastName, int prefixId, int suffixId,
			boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
			String jobTitle, long[] groupIds, long[] organizationIds,
			long[] roleIds, long[] userGroupIds, boolean sendEmail,
			ServiceContext serviceContext) throws PortalException,
			SystemException {
		
		
		Organization organization = null;

		if(!middleName.equals("student")){
			
			try {
				long defaultUserId = UserLocalServiceUtil.getDefaultUserId(companyId);
				organization = setupOrganizations(companyId, defaultUserId, openId, jobTitle);
			
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		lastName += StringPool.PERIOD;
		
		User user = super.addUser(creatorUserId, companyId, autoPassword, password1,
				password2, autoScreenName, screenName, emailAddress, facebookId,
				openId, locale, firstName, "", lastName, prefixId, suffixId,
				male, birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds,
				organizationIds, roleIds, userGroupIds, sendEmail, serviceContext);
		
		if(Validator.isNotNull(organization)) {
			Role role1 = RoleLocalServiceUtil.getRole(companyId, RoleConstants.ORGANIZATION_OWNER);
			if(role1 != null){
				
				UserLocalServiceUtil.addRoleUsers(role1.getRoleId(), new long[]{user.getUserId()});
				UserLocalServiceUtil.addOrganizationUsers(organization.getOrganizationId(), new long[]{user.getUserId()});
				UserGroupRoleLocalServiceUtil.addUserGroupRoles(new long[]{user.getUserId()},user.getGroup().getGroupId(), role1.getRoleId());
			}
		}
		
		return user;
	}
	
	protected Organization setupOrganizations(long companyId, long defaultUserId, String name, String type)
		throws Exception {
		
		long userId = defaultUserId;
		long parentOrganizationId = OrganizationConstants.DEFAULT_PARENT_ORGANIZATION_ID;
		boolean recursable = true;
		long regionId = 0;
		long countryId = 0;
		int statusId = GetterUtil.getInteger(PropsUtil.get(
			"sql.data.com.liferay.portal.model.ListType.organization.status"));
		String comments = null;

		ServiceContext serviceContext = new ServiceContext();

		serviceContext.setAddCommunityPermissions(true);
		serviceContext.setAddGuestPermissions(true);

		Organization organization =
			OrganizationLocalServiceUtil.addOrganization(
				userId, parentOrganizationId, name, type, recursable, regionId,
				countryId, statusId, comments, serviceContext);
		// Indexer
		Indexer indexer = IndexerRegistryUtil.getIndexer(Organization.class);
		indexer.reindex(organization);   
		
		// Group
		Group group = organization.getGroup();

		// Layout set

		LayoutSetLocalServiceUtil.updateLogo(
			group.getGroupId(), false, true,
			getInputStream("/sample/images/liferay_logo.png"));
		
		// Home layout
		addLayout(group, "Home", false, "/home", "home");
		
		return organization;

	}
	
	protected Layout addLayout(
			Group group, String name, boolean privateLayout, String friendlyURL,
			String layouteTemplateId)
		throws Exception {
		ServiceContext serviceContext = new ServiceContext();
		Layout layout = LayoutLocalServiceUtil.addLayout(
			group.getCreatorUserId(), group.getGroupId(), privateLayout,
			LayoutConstants.DEFAULT_PARENT_LAYOUT_ID, name, StringPool.BLANK,
			StringPool.BLANK, LayoutConstants.TYPE_PORTLET, false, friendlyURL,
			serviceContext);
		return layout;
	}	
	
	protected void addResources(Layout layout, String portletId)
	throws Exception{

		String rootPortletId = PortletConstants.getRootPortletId(portletId);
	
		String portletPrimaryKey = PortletPermissionUtil.getPrimaryKey(
			layout.getPlid(), portletId);
	
		ResourceLocalServiceUtil.addResources(
			layout.getCompanyId(), layout.getGroupId(), 0, rootPortletId,
			portletPrimaryKey, true, true, true);
	}
	
	protected InputStream getInputStream(String path) throws Exception {
		ClassLoader classLoader = getClass().getClassLoader();

		return classLoader.getResourceAsStream("/resources" + path);
	}

}